﻿/**
 * @copyright Copyright 2009 Structured Solutions
 * @license http://www.codeplex.com/ShippingAgent/license Microsoft Public License (Ms-PL)
 * @version 3.2
 */

using System;
using System.Collections.Generic;

namespace StructuredSolutions.ShippingAgent
{
    /// <summary>
    /// NamedAmountList treats each name and description combination as a unique entry.
    /// It also allows easy coding to the list. For example, you do not need to add the
    /// entry before you use it.
    /// <example>
    /// var list = new NamedAmountList();
    /// list["Total"].Amount += 5;
    /// list["Discount", "20% Off"].Amount += 6;
    /// </example>
    ///  </summary>
    public class NamedAmountList : List<NamedAmount>
    {
        public NamedAmount this[string name]
        {
            get { return this[name, null]; }    
            set { this[name, null] = value; }
        }

        public NamedAmount this[string name, string description]
        {
            get
            {
                var index = IndexOf(name, description);
                if (index > -1)
                {
                    return this[index];
                }
                NamedAmount amount = new NamedAmount();
                amount.Amount = 0;
                amount.Description = description;
                amount.Name = name;
                Add(amount);
                return amount;
            }
            set
            {
                var index = IndexOf(name, description);
                if (index > -1)
                    this[index] = value;
                else
                    Add(value);
            }
        }

        public int IndexOf(string name)
        {
            return IndexOf(name, null);
        }

        public int IndexOf(string name, string description)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            for (var index = 0; index < Count; index++)
            {
                var amount = this[index];
                if (!name.Equals(amount.Name, StringComparison.InvariantCultureIgnoreCase))
                    continue;
                if (string.IsNullOrEmpty(description))
                {
                    if (!string.IsNullOrEmpty(amount.Description))
                        continue;
                }
                else
                {
                    if (!description.Equals(amount.Description, StringComparison.InvariantCultureIgnoreCase))
                        continue;
                }

                return index;
            }
            return -1;
        }
    }
}